package com.lagouedu.controller;

import com.lagouedu.pojo.R;
import com.lagouedu.sevice.CodeFeign;
import com.lagouedu.sevice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private CodeFeign codeFeign;

    @RequestMapping("/register/{email}/{password}/{code}")
    public R register(@PathVariable("email") String email,@PathVariable("password") String password,@PathVariable("code") String code){
        // 1、校验验证码是否正确
        R validate = codeFeign.validate(email, code);
        int code1 = (int) validate.get("code");
        if(code1 != 200){
            return validate;
        }
        // 2、根据用户名和密码生成token 存入数据库
        userService.saveEmailAndToken(email,userService.generateToken(email+password));
        return R.ok("注册成功");
    }

    @RequestMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email){
        return userService.isRegistered(email);
    }

    @RequestMapping("/login/{email}/{password}")
    public R login(@PathVariable("email")String email, @PathVariable("password")String password){
        // 校验用户名和密码合法性
        String token = userService.validateUser(email, password);
        if(!"".equals(token)){
            R r = R.ok("登录成功");
            r.put("email", email);
            r.put("token", token);
            return r;
        }else{
            return R.error("用户名密码校验失败");
        }
    }

    @RequestMapping("/info/{token}")
    public R getEmailByToken(@PathVariable("token") String token){
        if (StringUtils.isEmpty(userService.getEmailByToken(token))){
            return R.error("token 校验失败");
        }
        return R.ok(userService.getEmailByToken(token));
    }
}
